'use strict';
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var glob = require('glob-all');
var PurifyCssPlugin = require('purifycss-webpack');
var openBrowserPlugin = require('open-browser-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, './app');
var LIB_PATH = path.resolve(ROOT_PATH, './lib');

var BUILD_PATH = path.resolve(ROOT_PATH, '../../../../../../../dz-boss-test');

if ("pre" == process.env.PACKAGE_ENV) {
    BUILD_PATH = path.resolve(ROOT_PATH, '../../../../../../../dz-boss-pre');
}

if ("production" == process.env.PACKAGE_ENV) {
    BUILD_PATH = path.resolve(ROOT_PATH, '../../../../../../../dz-boss-pro');
}


//var BUILD_PATH = path.resolve(ROOT_PATH, '/../../techwolf-blue/techwolf-blue-wep/src/main/webapp/html');
var MODULES_PATH = path.resolve(ROOT_PATH, './node_modules');
var DEFAULT = path.resolve(APP_PATH, 'default');
var HtmlwebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

var plugins = [

    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: '"production"'
        }
    }),

    new CleanWebpackPlugin(
        [BUILD_PATH + '/*'],　 //匹配删除的文件
        {
            root: BUILD_PATH,       　　　　　　　　　　//根目录
            verbose: true,        　　　　　　　　　　//开启在控制台输出信息
            dry: false        　　　　　　　　　　//启用删除文件
        }
    ),

    new webpack.ContextReplacementPlugin(
        /moment[\\\/]locale$/,
        /^\.\/(zh-cn)$/
        ///(zh-cn)\.js/
    ),

    new webpack.ProvidePlugin({
        Axios: "axios",
        React: "react",
        ReactDOM: 'react-dom',
        Router: ["react-router", "Router"],
        Route: ["react-router", "Route"],
        Link: ["react-router", "Link"],
        ClassNames: ["classnames"],
        PropTypes: ["prop-types"],
        Immer: ["immer", "default"],
        Connect: ["react-redux", "connect"],
        ActionTypes: "@/redux/action-types",
        Actions: ["@/redux/actions/index", "default"],
        Invoke: ["@/invoke/index", "default"]
    }),

    new webpack.optimize.CommonsChunkPlugin({
        name: 'common',
        filename: 'js/common-[chunkhash:6].js',
        minChunks: 3
    }),

    //new webpack.optimize.CommonsChunkPlugin({
    //    children: true,
    //    async: "common_async",
    //    minChunks: 3
    //}),

    new ExtractTextPlugin({ filename: 'css/[name]-[contenthash:6].css', allChunks: true }),

    //new PurifyCssPlugin({
    //    paths: glob.sync([
    //        path.join(APP_PATH, '/components/**/*.jsx'),
    //        path.join(APP_PATH, '/components/**/*.js')
    //    ]),
    //    minimize: true,
    //    styleExtensions: ['.scss', ".css"],
    //}),

    new webpack.optimize.UglifyJsPlugin({
        //sourceMap: true,
        compress: {
            warnings: false,
            drop_debugger: true, // 发布时去除debugger语句
            drop_console: true // 发布时去除console语句
        }
    }),

];

var entris = fs.readdirSync(APP_PATH).reduce(function (o, filename) {
    if (/\.js/g.test(filename)) {
        var _name = filename.replace(/\.js$|\.jsx$/g, '');
        //o[_name] = ["react-hot-loader/patch", path.resolve(APP_PATH, filename)];
        o[_name] = path.resolve(APP_PATH, filename);
        var html = new HtmlwebpackPlugin({
            title: '店长商业版本',
            filename: _name + '.html',
            chunks: ["common", _name],
            favicon: path.resolve(DEFAULT, 'favicon.ico'),
            hash: false,
            template: path.resolve(DEFAULT, 'default-template.html'),
            minify: {
                removeComments: true,       //去掉注释
                //collapseWhitespace: true    //去掉空格
            }
        });
        plugins.push(html);
    }
    return o;
}, { "common": ['babel-polyfill', "react", "react-dom", "react-router"] });

module.exports = {
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.(js|jsx)?$/,
                use: ['babel-loader'],
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        //blacklist: ["useStrict"],
                        babelrc: false,
                        presets: ['env', 'react', 'stage-0'],
                        plugins: ["transform-remove-strict-mode"]
                        //, plugins: ["react-hot-loader/babel"]   //react-hot-loader/patch 不写记录不到状态
                    }
                }
            },
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                sourceMap: true,
                                minimize: true //css压缩
                            }
                        },
                        'postcss-loader',
                        'sass-loader'
                    ],
                    publicPath: "../"
                })
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                sourceMap: true,
                                minimize: true //css压缩
                            }
                        },
                        'postcss-loader'
                    ],
                    publicPath: "../"
                })
            },
            {
                test: /\.(png|jpeg|jpg|gif)$/,
                use: {
                    loader: "url-loader",
                    options: {
                        limit: "20000",
                        name: "img/[name]-[hash:6].[ext]"
                    }
                }
            }
        ]
    },

    entry: entris,

    output: {
        filename: 'js/[name]-[chunkhash:6].js',
        chunkFilename: 'js/[name]-[chunkhash:6].js',
        path: BUILD_PATH,
        //publicPath: '/html/'
    },

    resolve: {
        extensions: ['.js', '.jsx', '.json', 'css'],
        modules: ["node_modules", path.resolve(__dirname, 'app')],
        alias: {
            '@': path.resolve(__dirname, 'app'),
            'react': path.resolve(MODULES_PATH, './react'),
            'react-dom': path.resolve(MODULES_PATH, './react-dom'),
            'my-default-style': path.resolve(DEFAULT, './default-style.css'),
            'base': path.resolve(LIB_PATH, './base.js'),
            'vali': path.resolve(LIB_PATH, './vali.js'),
            'api': path.resolve(LIB_PATH, './api.js')
        }
    },

    plugins: plugins

};